import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { map } from "rxjs";

@Injectable()
export class ResponseInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(
      map((data) => {
        /** 
         * undefined默认为成功
         */
        if (data===undefined) return {
          success: true,
          data: {}
        }
        /**
         * 数组和对象包一层
         */
        if (['[object Array]', '[object Object]'].includes(Object.prototype.toString.call(data))) {
          /** 
           * 已经包过就不包了
           */
          const keys = Object.keys(data);
          if (keys.includes('success') && keys.includes('data')) return data;
          /** 
           * 包一层
           */
          return ({
            success: true,
            data,
          })
        }
        /** 其他情况不做处理 */
        return data;
      })
    )
  }
}